package sandbox;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.joda.time.Instant;

public final class StateList {
	private static volatile List<State> followingStates = new ArrayList<State>();

	public static List<State> getFollowingStates(){
		return followingStates;
	}
	
	public void addState(Instant theStateTime,
			Set<Decision> decisionsTakenInThisState) {
		followingStates.add(new State(theStateTime, decisionsTakenInThisState));
	}
	
	public static State getLastState() {
		if (followingStates == null || followingStates.size() < 1)
			return null;
		Collections.sort(followingStates);
		return followingStates.get(followingStates.size() - 1);
	}

	public class State implements Comparable<State> {
		private Instant theStateTime;
		private Set<Decision> decisionsTakenInThisState;
		
		@Override
		public String toString() {
			String dec = "";
			if(decisionsTakenInThisState != null && decisionsTakenInThisState.size()>0){
				dec = ", decisions taken in this state:";
			for (Decision d : decisionsTakenInThisState) {
				dec += ("\n" + d.toString());
			}}
			return "\nThe state time: " + theStateTime.getMillis() + dec; 
		}

		public Instant nextStateTime() {
			if (decisionsTakenInThisState == null
					|| decisionsTakenInThisState.size() < 1)
				return null;
			Instant nextStateTime = new Instant(Long.MAX_VALUE);
			for (Decision decision : decisionsTakenInThisState) {
				if (decision.getWhenTheWorkFinishes().isBefore(nextStateTime))
					nextStateTime = decision.getWhenTheWorkFinishes();
			}
			return nextStateTime;
		}

		public Instant getTheStateTime() {
			return theStateTime;
		}

		public Set<Decision> getDecisionsTakenInThisState() {
			return decisionsTakenInThisState;
		}

		private State(Instant theStateTime,
				Set<Decision> decisionsTakenInThisState) {
			this.theStateTime = theStateTime;
			this.decisionsTakenInThisState = decisionsTakenInThisState;
		}

		@Override
		public int compareTo(State o) {
			return this.theStateTime.compareTo(o.theStateTime);
		}
	}
}
